<template>
  <div v-if="startWith === 'init'" style="height: 100%">
    <div style="width: 312px; margin: 0 auto" v-if="currentStackFrame === 0">
      <div
        style="
          font-size: 18px;
          font-weight: 800;
          text-align: center;
          margin-top: 30px;
        "
      >
        What is a Wallet?
      </div>
      <div
        style="display: flex; gap: 16px; align-items: center; margin-top: 32px"
      >
        <Asstes style="flex-shrink: 0" />
        <div style="font-size: 14px; line-height: 18px">
          <div style="color: white; margin-bottom: 4px; font-weight: bold">
            A Home for your Digital Assets
          </div>
          <div style="color: #ffffff99">
            Wallets are used to send, receive, store, and display digital assets
            like Ethereum and NFTs.
          </div>
        </div>
      </div>
      <div
        style="display: flex; gap: 16px; align-items: center; margin-top: 32px"
      >
        <Login style="flex-shrink: 0" />
        <div style="font-size: 14px; line-height: 18px">
          <div style="color: white; margin-bottom: 4px; font-weight: bold">
            A New Way to Log In
          </div>
          <div style="color: #ffffff99">
            Instead of creating new accounts and passwords on every website,
            just connect your wallet.
          </div>
        </div>
      </div>
      <div
        style="
          display: flex;
          gap: 16px;
          align-items: center;
          margin-top: 48px;
          justify-content: center;
        "
      >
        <button @click="getWallet">Get a Wallet</button>
      </div>
      <div
        style="
          display: flex;
          gap: 16px;
          align-items: center;
          margin-top: 10px;
          justify-content: center;
        "
      >
        <button
          @click="learnMore()"
          style="background: transparent; color: #d9fc01"
        >
          Learn More
        </button>
      </div>
    </div>
    <div
      v-else-if="currentStackFrame === 1"
      style="
        margin-top: 30px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
      "
    >
      <div
        style="
          height: 320px;
          overflow-x: hidden;
          overflow-y: auto;
          scrollbar-width: thin;
        "
      >
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-bottom: 28px;
            align-items: center;
          "
          v-for="item in initState.shownWallets"
          :key="item.id"
        >
          <div style="display: flex; gap: 16px">
            <img
              style="width: 48px; height: 48px; border-radius: 8px"
              :src="item.icon ?? item.iconUrl"
            />
            <div style="font-size: 14px">
              <div style="font-weight: bold">{{ item.name }}</div>
              <div style="color: #ffffff99">
                {{ getWalletDetailMinLabel(item) }}
              </div>
            </div>
          </div>
          <button
            style="height: 24px"
            @click="
              () => {
                emits('changeStep', {
                  stackFrame: 2,
                  modalTitle: 'Get ' + item.name,
                })
                beforUseWallet = item
              }
            "
          >
            GET
          </button>
        </div>
      </div>
      <div
        style="
          font-size: 14px;
          text-align: center;
          max-width: 275px;
          line-height: 18px;
          margin: 0 auto;
          margin-top: 16px;
        "
      >
        <div style="font-weight: bold; margin-bottom: 8px">
          Not what you're looking for?
        </div>
        <div style="color: #ffffff99">
          Select a wallet on the left to get started with a different wallet
          provider.
        </div>
      </div>
    </div>
    <div v-if="currentStackFrame === 2" style="height: 100%">
      <DownloadOptions
        :wallet="beforUseWallet"
        style="padding-top: 16px; margin-top: 0"
        @add-to-browser="addToBrowser"
        @add-to-desktop="addToDesktop"
        @add-to-mobile="addToMobile"
      />
    </div>
    <InstructionOptions
      v-else-if="currentStackFrame === 3"
      :uid="DesktopModalConstant?.CONTEXT_UID"
      style="margin-top: 16px"
      :stack-frame="currentStackFrame"
      :wallet="beforUseWallet"
      @learn-more="
        learnMore(beforUseWallet.extension?.instructions?.learnMoreUrl)
      "
      @continue="addAppContinue(beforUseWallet)"
      @connect="connect(wallet)"
      @refresh="refresh"
    />
    <!--  只有移动端添加app会走到这里  -->
    <InstructionMobileContent
      v-else-if="currentStackFrame === 4"
      style="margin-top: 16px"
      :wallet="beforUseWallet"
      @connect="connect(beforUseWallet)"
      @learn-more="learnMore(beforUseWallet.qrCode?.instructions?.learnMoreUrl)"
    />
  </div>
  <div v-else-if="startWith === 'noExtAndHaveApp'" style="height: 100%">
    <DownloadContent
      v-if="currentStackFrame === 0"
      style="margin-top: 16px"
      :wallet="wallet"
      @get="
        () => {
          emits('changeStep', {
            stackFrame: 1,
            modalTitle: 'Get ' + wallet.name,
          })
        }
      "
      @open="() => emits('openOfficialWalletConnectModal')"
    />
    <div v-if="currentStackFrame === 1" style="height: 100%">
      <DownloadOptions
        :wallet="wallet"
        style="padding-top: 16px; margin-top: 0"
        @add-to-browser="addToBrowser"
        @add-to-desktop="addToDesktop"
        @add-to-mobile="addToMobile"
      />
    </div>
    <InstructionOptions
      v-else-if="currentStackFrame === 2"
      :uid="DesktopModalConstant?.CONTEXT_UID"
      style="margin-top: 16px"
      :stack-frame="currentStackFrame"
      :wallet="wallet"
      @learn-more="learnMore(wallet.extension?.instructions?.learnMoreUrl)"
      @continue="addAppContinue(wallet)"
      @connect="connect(wallet)"
      @refresh="refresh"
    />
    <!--  只有移动端添加app会走到这里  -->
    <InstructionMobileContent
      v-else-if="currentStackFrame === 3"
      style="margin-top: 16px"
      :wallet="wallet"
      @connect="connect(wallet)"
      @learn-more="learnMore(wallet.qrCode?.instructions?.learnMoreUrl)"
    />
  </div>
  <div v-else style="height: 100%">
    <div v-if="currentStackFrame === 0" style="height: 100%">
      <DownloadOptions
        :wallet="wallet"
        style="padding-top: 16px; margin-top: 0"
        @add-to-browser="addToBrowser"
        @add-to-desktop="addToDesktop"
        @add-to-mobile="addToMobile"
      />
    </div>
    <InstructionOptions
      v-else-if="currentStackFrame === 1"
      :uid="DesktopModalConstant?.CONTEXT_UID"
      style="margin-top: 45px"
      :stack-frame="currentStackFrame"
      :wallet="wallet"
      @learn-more="learnMore(wallet.extension?.instructions?.learnMoreUrl)"
      @continue="addAppContinue(wallet)"
      @connect="connect(wallet)"
      @refresh="refresh"
    />
    <!--  只有移动端添加app会走到这里  -->
    <InstructionMobileContent
      v-else-if="currentStackFrame === 2"
      style="margin-top: 45px"
      :wallet="wallet"
      @connect="connect(wallet)"
      @learn-more="learnMore(wallet.qrCode?.instructions?.learnMoreUrl)"
    />
  </div>
</template>
<script setup lang="ts">
import Asstes from '../Icons/Asstes.vue'
import Login from '../Icons/Login.vue'
import { useWalletConnectors, type WalletConnector } from '../../wallets/useWalletConnectors'
import { onMounted, reactive, ref } from 'vue'
import DownloadOptions from '../Modal/DownloadOptions.vue'
import InstructionMobileContent from './InstructionMobileContent.vue'
import InstructionOptions from './InstructionOptions.vue'
import { useHasCondition } from '../../hooks/useHasCondition'
import DownloadContent from '../Modal/DownloadContent.vue'
import { DesktopModalConstant } from '../../constants/ModalContextConstant'

const emits = defineEmits([
  'openOfficialWalletConnectModal',
  'changeStep',
  'update:wallet',
])
const props = withDefaults(
  defineProps<{
    currentStackFrame?: number
    wallet?: WalletConnector
    startWith: 'init' | 'noExtAndHaveApp' | 'noExtAndApp'
  }>(),
  {
    currentStackFrame: 0,
    // @ts-ignore
    wallet: {} as WalletConnector,
  },
)

const initState = reactive<any>({
  shownWallets: [],
})

// 在未选择钱包时去获取的暂存钱包，
// 走完用户引导流程会需要跳转这个钱包
const beforUseWallet = ref()

const initContentData = () => {
  if (props.startWith === 'init') {
    const wallets = useWalletConnectors().filter(
      wallet =>
        wallet.isWalletKitConnector &&
        (wallet.extensionDownloadUrl ||
          wallet.desktopDownloadUrl ||
          (wallet.qrCode && wallet.downloadUrls?.qrCode)),
    )

    // 看看是否需要只取前几个钱包展示
    initState.shownWallets = wallets
  }
}

const getWalletDetailMinLabel = (wallet: WalletConnector) => {
  const { getContentCondition } = useHasCondition(wallet)
  return getContentCondition.value.hasMobileAndExtension
    ? 'Mobile Wallet and Extension'
    : getContentCondition.value.hasMobileAndDesktop
      ? 'Mobile and Desktop Wallet'
      : getContentCondition.value.hasMobileCompanionApp
        ? 'Mobile Wallet'
        : getContentCondition.value.hasExtension
          ? 'Browser Extension'
          : null
}

const getWallet = () => {
  emits('changeStep', {
    stackFrame: 1,
    modalTitle: 'Get a Wallet',
  })
}

const learnMore = (url?: string) => {
  if (url) {
    window.open(url, '_blank')
    return
  }
  window.open(
    'https://learn.rainbow.me/understanding-web3?utm_source=rainbowkit&utm_campaign=learnmore',
    '_blank',
  )
}

const addToBrowser = (wallet: WalletConnector) => {
  if (wallet.extension?.instructions) {
    window.open(wallet.extensionDownloadUrl, '_blank')
    emits('changeStep', {
      stackFrame: props.currentStackFrame + 1,
      modalTitle: 'Get started with ' + wallet.name,
      type: 'browser',
    })
  } else {
    goInitStack(wallet)
    if (wallet.ready) {
      wallet.connect()
    }
  }
}
const addToMobile = (wallet: WalletConnector) => {
  emits('changeStep', {
    stackFrame: props.currentStackFrame + 1,
    modalTitle: 'Install ' + wallet.name,
    type: 'mobile',
  })
}
const addToDesktop = (wallet: WalletConnector) => {
  if (wallet.desktop?.instructions) {
    window.open(wallet.desktopDownloadUrl, '_blank')
    emits('changeStep', {
      stackFrame: props.currentStackFrame + 1,
      modalTitle: 'Get started with ' + wallet.name,
      type: 'desktop',
    })
  } else {
    goInitStack(wallet)
    if (wallet.ready) {
      wallet.connect()
    }
  }
}

const addAppContinue = (wallet: WalletConnector) => {
  if (wallet.qrCode?.instructions) {
    emits('changeStep', {
      stackFrame: props.currentStackFrame + 1,
      modalTitle: 'Get started with ' + wallet.name,
    })
  } else {
    goInitStack(wallet)
    if (wallet.ready) {
      wallet.connect()
    }
  }
}

const connect = (wallet: WalletConnector) => {
  beforUseWallet.value = undefined
  if (wallet.id === 'coinbase') {
    goInitStack(wallet)
    if (wallet.ready) {
      wallet.connect()
    }
  } else {
    goInitStack(wallet)
  }
}

const goInitStack = (wallet: WalletConnector) => {
  emits('update:wallet', wallet)
  if (!wallet.ready) {
    emits('changeStep', {
      stackFrame: 0,
      modalTitle: 'Get ' + wallet.name,
    })
  } else {
    if (
      wallet.getQrCodeUri &&
      wallet.isWalletKitConnector &&
      wallet.id !== 'coinbase'
    ) {
      emits('changeStep', {
        stackFrame: 0,
        modalTitle: 'Scan with ' + wallet.name,
      })
    } else {
      emits('changeStep', {
        stackFrame: 0,
        modalTitle: '',
      })
    }
  }
}

const refresh = () => {
  window.location.reload()
}

onMounted(() => {
  initContentData()
})
</script>

<style lang="scss" scoped>
button {
  cursor: pointer;
  padding: 4px 12px;
  transition: all 0.3s ease;
  border: none;
  background: #d9fc01;
  color: #1a1b1f;
  border-radius: 24px;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: -0.05em;
  line-height: 16px;
  &:hover {
    transform: scale(1.05);
  }
  &:active {
    transform: scale(0.95);
  }
}
</style>
